import { Controller, Get, Post, Put, Delete, Body, Param, Query, UseGuards } from '@nestjs/common';
import { PermissionService } from './permission.service';
import { JwtAuthGuard } from '../../guards/jwt-auth.guard';
import { RolesGuard } from '../../guards/roles.guard';
import { PermissionsGuard } from '../../guards/permissions.guard';
import { Roles } from '../../decorators/roles.decorator';
import { Permissions } from '../../decorators/permissions.decorator';
import { ApiTags, ApiOperation, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { PermissionGroup } from '../../entities/permission.entity';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';

@ApiTags('权限管理')
@Controller('permissions')
@UseGuards(JwtAuthGuard, RolesGuard, PermissionsGuard)
@ApiBearerAuth()
@Roles('系统管理员')
export class PermissionController {
  constructor(private permissionService: PermissionService) {}

  @Post()
  @Permissions('system:permission:create')
  @ApiOperation({ summary: '创建权限' })
  @ApiResponse({ status: 201, description: '权限创建成功' })
  async createPermission(
    @Body() createPermissionDto: CreatePermissionDto
  ) {
    return this.permissionService.createPermission(
      createPermissionDto.name,
      createPermissionDto.code,
      createPermissionDto.group,
      createPermissionDto.description
    );
  }

  @Put(':id')
  @Permissions('system:permission:update')
  @ApiOperation({ summary: '更新权限' })
  @ApiResponse({ status: 200, description: '权限更新成功' })
  async updatePermission(
    @Param('id') id: string,
    @Body() updatePermissionDto: UpdatePermissionDto
  ) {
    return this.permissionService.updatePermission(
      id,
      updatePermissionDto.name,
      updatePermissionDto.code,
      updatePermissionDto.group,
      updatePermissionDto.description
    );
  }

  @Delete(':id')
  @Permissions('system:permission:delete')
  @ApiOperation({ summary: '删除权限' })
  @ApiResponse({ status: 200, description: '权限删除成功' })
  async deletePermission(@Param('id') id: string) {
    return this.permissionService.deletePermission(id);
  }

  @Get()
  @Permissions('system:permission:read')
  @ApiOperation({ summary: '获取权限列表' })
  @ApiResponse({ status: 200, description: '获取权限列表成功' })
  async getPermissions(@Query('group') group?: PermissionGroup) {
    if (group) {
      return this.permissionService.getPermissionsByGroup(group);
    }
    return this.permissionService.getPermissions();
  }

  @Get(':id')
  @Permissions('system:permission:read')
  @ApiOperation({ summary: '获取权限详情' })
  @ApiResponse({ status: 200, description: '获取权限详情成功' })
  async getPermissionById(@Param('id') id: string) {
    return this.permissionService.getPermissionById(id);
  }
} 